import Gobj from "./Gobj";

export default class GMap{
    objMap = {};
    objArr:Gobj[] = [];

    addObj(obj:Gobj){
        if(this.objMap[obj.key]){
            throw new Error('重复的添加 ' + obj.key);
        }
        this.objMap[obj.key] = obj;        
        this.objArr.push(obj);
    }

    existKey(key):boolean{
        if(this.objMap[key]){
            return true;
        }
        return false;
    }

    getObj(key):Gobj{
        if(this.existKey(key)){
            return this.objMap[key] as Gobj;
        }
        return null;
    }

    removeobj(key){
        //console.log(" remove obj key " ,key);        
        if(this.objMap[key]){
            var o = this.objMap[key]
            this.objArr.splice( this.objArr.indexOf(o),1);
            delete this.objMap[key];
            //console.log(" remove obj key OK :: " ,o.key);        
            return o;
        }
        return null;
    }

    sortArr(){
        this.objArr.sort((a,b)=>{
            return a.id - b.id;
        });
    }

    syncTime(uid:number,other:GMap){
        var omap = other.objMap;
        var mmap =  this.objMap;

        //同步两个宇宙的对象数据
        for (const key in omap) {
            let oobj = omap[key] as Gobj;
            let mobj = mmap[key] as Gobj;
            if(mobj){//如果存在 就同步数据
                mobj.syncTime( oobj );
            }else{//如果不存在 就克隆一个数据
                mobj = oobj.copy();
                mobj.uid = uid;
                this.addObj(mobj);
            }
        }
        
        //同步删除不存在的对象数据
        var temp = [];
        for (const key in mmap) {            
            if(!omap[key]){
                //console.log("temp key " , key);            
                temp.push(key);
            }    
        }
        //console.log(" temp length " , temp.length );        
        while(temp.length>0){
            this.removeobj( temp.pop() );
        }

        // for (let i = 0; i < temp.length; i++) {
        //     const key = temp[i];
        //     this.removeobj(key);
        // }

        this.sortArr();
    }

}